//注销账户按钮
import React, { useState, useEffect } from "react";
import {Button, Checkbox, Form, Input, Modal, message} from 'antd'
import { Link, useRouter } from 'next/router';
import axios from 'axios';
const DeleteUser = () => {
    const router = useRouter();

    //展开对话框
    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
     };

    const handleOk = () => {
        setIsModalOpen(false);
        form.submit(); // 提交表单
    };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //对话框中的表单
  const [form] = Form.useForm();
  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 8,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 16,
      },
    },
  };

  const onFinish = (values) => {
    console.log('Request Body:', values); // 打印请求体内容
    const token = localStorage.getItem('token'); // 获取存储的token
  if (!token) {
    message.error('请先登录');
    router.push('/login');
    return;
  }
    axios.post('/api/user/delete', values, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
      .then((response) => {
        console.log('Success:', response.data);
        message.success('注销成功');
        // 使用router.push来导航到/main页面
        router.push('/'); 
      })
      .catch((error) => {
        console.log('Error:', error);
        // 登录失败时的处理
        if (error.response) {
          // 服务器返回了错误响应
          const errorMessage = error.response.data.msg || '注销失败';
          message.error(errorMessage);
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          message.error('请求失败，请检查网络连接');
        } else {
          // 发送请求时出了问题
          message.error('请求失败，请检查后端服务是否可用');
        }
      });
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

return (
    <>
      <Button type="primary" block danger onClick={showModal}>注销账户</Button>
      <Modal title="注销账户" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
      <Form
    {...formItemLayout}
    form={form}
    name="register"
    onFinish={onFinish}
    onFinishFailed={onFinishFailed}
    style={{
      maxWidth: 600,
    }}
    scrollToFirstError
  >  

    <Form.Item
      name="password"
      label="Password"
      rules={[
        {
          required: true,
          message: 'Please input your password!',
        },
      ]}
      hasFeedback
    >
      <Input.Password />
    </Form.Item>
   </Form>
    </Modal>
    </>
);
    };
  export default DeleteUser;